<template>
  <div class="goods-container">
    <!-- 左侧图片区域 -->
    <div class="left">
      <div class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" :id="id" :checked="state" @change="onCheckedChange">
        <label class="custom-control-label" :for="id">
          <img :src="thumb" class="avatar" alt="">
        </label>
      </div>
    </div>
    <!-- 右侧商品区域 -->
    <div class="right">
      <!-- 标题 -->
      <div class="title">{{title}}</div>
      <div class="info">
        <!-- 单价 -->
        <span class="price">￥{{price}}</span>
        <div class="btns">
          <!-- 按钮区域 -->
          <button class="btn btn-light" @click="onBtnClick(-1)">-</button>
          <span class="count">{{count}}</span>
          <button class="btn btn-light" @click="onBtnClick(1)">+</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'EsGoods',
  props: {
    // 商品的 Id
    id: {
      type: Number,
      required: true,
    },
    // 商品的名称
    title: {
      type: String,
      required: true,
    },
    // 商品的图片
    thumb: {
      type: String,
      required: true,
    },
    // 商品的单价
    price: {
      type: Number,
      required: true,
    },
    // 商品的数量
    count: {
      type: Number,
      required: true,
    },
    // 商品的状态
    state: {
      type: Boolean,
      required: true,
    },
  },
  methods: {
    // 监听选中状态变化的事件
    onCheckedChange(e) {
      // 把商品的 id 和最新的 state 值传递给父组件
      // this.$emit('stateChange', {
      //   id: this.id,
      //   state: e.target.checked,
      // })
      console.log(e.target.checked  );
      this.$store.commit('cart/updateState',{

        id:this.id,goods_state:e.target.checked
      })
    },
    // 按钮的点击事件处理函数
    onBtnClick(step) {
      // 如果新值 < 1，则不进行任何处理
      if (this.count + step < 1) {
        return
      }
      // 把商品的 id 和最新的 count 值传递给父组件
      // this.$emit('countChange', {
      //   id: this.id,
      //   count: this.count + step,
      // })
      this.$store.commit('cart/updateCount',{id:this.id,count:this.count + step})
    },
  },
}
</script>

<style lang="less" scoped>
.goods-container {
  display: flex;
  padding: 10px;
  + .goods-container {
    border-top: 1px solid #f8f8f8;
  }
  .left {
    .avatar {
      width: 100px;
      height: 100px;
    }
    margin-right: 10px;
  }
  .right {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    .title {
      font-weight: bold;
    }
    .info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .price {
        color: red;
        font-weight: bold;
      }
      .btns {
        .count {
          display: inline-block;
          width: 30px;
          text-align: center;
        }
      }
    }
  }
}

.custom-control-label::before,
.custom-control-label::after {
  top: 3.6rem;
}
</style>